﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace Server___console___class
{
    public partial class Form1 : Form
    {
        Thread _listenThread;
        Server _server;
        ServerLogger _log;

        public Form1()
        {
            InitializeComponent();
            _log = new ServerLogger();
            txbIP.Text = myIP();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            _server = new Server(this, Convert.ToInt32(txbPort.Text));
            _server.ServerStart();
            _listenThread = new Thread(new ThreadStart(_server.ListenForClients));
            _listenThread.Start();
        }

        public void AsyncWriteLine(String text)
        {
            richTextBox.BeginInvoke(new MethodInvoker(delegate
            {
                richTextBox.Text += DateTime.Now + " " + text + Environment.NewLine;
                _log.Log(text);
            }));
        }

    

        private void btnStop_Click(object sender, EventArgs e)
        {
            serverStop();
        }

        private void serverStop()
        {
            try
            {
                if (_listenThread.IsAlive)
                {
                    _server.TcpListener.Stop();
                    _listenThread.Abort();
                    _listenThread.Join();
                    AsyncWriteLine("Server stop");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private string myIP()
        {
            IPHostEntry host;
            string localIP = "?";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP = ip.ToString();
                }
            }
            return localIP;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            serverStop();
            this.Close();
        }

        private void btnAkcStart_Click(object sender, EventArgs e)
        {
            if (_listenThread.IsAlive)
            {
                _server.WriteToAllStreams("666");
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            serverStop();
            _server.ServerClose();
        }

        private void richTextBox_TextChanged(object sender, EventArgs e)
        {
            //richTextBox.SelectionStart = richTextBox.Text.Length;
            //richTextBox.ScrollToCaret();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

    }
}
